#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import json
import logging
import re
from utils import utils_data, ErrorInfoBuilder

logger = logging.getLogger('my_logger')


def build_error_info(relative_path, defect_type, description, main_buggy_line, main_buggy_code):
    return ErrorInfoBuilder() \
       .set_buggy_file_path(relative_path) \
       .set_defect_type(defect_type) \
       .set_description(description) \
       .set_main_buggy_line(main_buggy_line) \
       .set_main_buggy_code(main_buggy_code) \
       .build()


def write_error_and_log(error_info):
    utils_data.write_error_to_json_file(error_info)
    logger.info(json.dumps(error_info, indent=4, ensure_ascii=False))


def extract_content_block(content_lines, start_index):
    block_lines = []
    block_depth = 1
    for inner_idx in range(start_index + 1, len(content_lines)):
        block_lines.append(content_lines[inner_idx])
        block_depth += content_lines[inner_idx].count('{')
        block_depth -= content_lines[inner_idx].count('}')
        if block_depth == 0:
            end_index = inner_idx + 1
            break
    return "".join(block_lines), end_index


def check_hapname():
    file_entities = utils_data.get_file()
    if not file_entities:
        logger.error("未获取到文件信息")
        return

    has_error = False

    for entity in file_entities:
        if entity.file_name == "BUILD.gn":
            file_path = entity.full_path
            relative_path = entity.file_path
            with open(file_path, 'r', encoding='utf-8') as file:
                content_lines = file.readlines()

                for line_idx, line in enumerate(content_lines):
                    if re.match(r'ohos_js_app_suite\(".*"\)\s*\{', line):
                        start_line = line_idx + 1
                        block_content, _ = extract_content_block(content_lines, line_idx)

                        hap_name_match = re.search(r'hap_name\s*=\s*"(.*)"', block_content)
                        if hap_name_match:
                            hap_name = hap_name_match.group(1)
                            if not re.match(r'^(Acts|Dcts|Hats).*Test$', hap_name):
                                main_buggy_line = start_line + block_content[:hap_name_match.start()].count(
                                    '\n') + 1
                                error_info = build_error_info(
                                    relative_path,
                                    "XTS.CHECK.HAPNAME.01",
                                    "hap_name不符合XTS命名规范",
                                    main_buggy_line,
                                    hap_name_match.group(0)
                                )
                                write_error_and_log(error_info)
                                has_error = True

                        hap_list_items = re.findall(r'hap_list\s*=\s*\[\s*([^]]+)\s*\]', block_content, re.DOTALL)
                        all_hap_list_items = []
                        for item in hap_list_items:
                            sub_items = re.findall(r'"([^"]+)"', item)
                            all_hap_list_items.extend(sub_items)

                        for hap_item in all_hap_list_items:
                            parts = hap_item.split(':')
                            if len(parts) > 1:
                                part_to_check = parts[1]
                                if not re.match(r'^(Acts|Dcts|Hats).*Test$', part_to_check):
                                    item_start_index = block_content.find(hap_item)
                                    if item_start_index!= -1:
                                        main_buggy_line = start_line + block_content[:item_start_index].count(
                                            '\n') + 1
                                        error_info = build_error_info(
                                            relative_path,
                                            "XTS.CHECK.HAPNAME.01",
                                            "hap_list中的值不符合XTS命名规范",
                                            main_buggy_line,
                                            hap_item
                                        )
                                        write_error_and_log(error_info)
                                        has_error = True
                                    else:
                                        logger.error(
                                            f"在处理 {relative_path} 文件中，未能准确找到 {hap_item} 在内容块中的位置，可能存在逻辑问题")
                            else:
                                logger.error(f"{hap_item} 格式不符合预期，无法进行正确校验（缺少':'分割）")

    if has_error:
        logger.info("测试组件hapname命名规范检查完成，错误信息已写入xts_result.json")
    else:
        logger.info("测试组件hapname命名规范检查通过")